#coding=utf-8
import datetime
import os
import traceback

from loguru import logger
from playwright.sync_api import sync_playwright


import aikucun.akc_common as akc_common

def group_by_period(job_list):
    job_group = {}
    period_list = list(set(map(lambda x: x['period'], job_list)))
    for period in period_list:
        filter_list = list(filter(lambda x: x['period'] == period, job_list))
        job_group[period] = filter_list
    return job_group


def akc_main(host, account_list):
    try:
        store_id_list = list(set(map(lambda x: x['storeId'], account_list)))
        with sync_playwright() as playwright:
            akc_func = akc_common.AKC(playwright, host, 'haiwangou-key')
            for store_id in store_id_list:
                store_job_list = list(filter(lambda x: x['storeId'] == store_id, account_list))
                # 按照周期分组，按每个周期循环运行，每跑完一个周期上传一次
                job_group = group_by_period(store_job_list)
                akc_func.login(store_job_list[0])
                for period, job_list in job_group.items():
                    logger.info(f'开始下载【{period}】周期的账单')
                    file_list = []
                    param_list = []
                    for item in job_list:
                        if item['accountType'] == '往期应收冲销':
                            logger.info('开始下载【往期应收冲销】流程...')
                            start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                            bill_file = akc_func.download_receive_bill(period)
                            if bill_file is not None:
                                file_list.append(bill_file)
                                dir_path, file_name = os.path.split(bill_file)
                                param_list.append({'orderType': '往期应收冲销', 'fileName': file_name, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                            else:
                                param_list.append({'orderType': '往期应收冲销', 'fileName': '无', 'period': period, 'logId': item['logId'], 'startTime': start_time})
                        if item['accountType'] == '账户出入款记录':
                            logger.info('开始下载【账户出入款记录】流程...')
                            start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                            bill_file = akc_func.download_owner_receive_bill(period)
                            if bill_file is not None:
                                dir_path, file_name = os.path.split(bill_file)
                                param_list.append({'orderType': '账户出入款记录', 'fileName': file_name, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                file_list.append(bill_file)
                            else:
                                param_list.append({'orderType': '账户出入款记录', 'fileName': '无', 'period': period, 'logId': item['logId'], 'startTime': start_time})
                        if item['accountType'] == '业务结算明细':
                            logger.info('开始下载【业务结算明细】流程')
                            start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                            bill_file = akc_func.download_business_detail(period)
                            if bill_file is not None:
                                dir_path, file_name = os.path.split(bill_file)
                                param_list.append({'orderType': '业务结算明细', 'fileName': file_name, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                file_list.append(bill_file)
                            else:
                                param_list.append({'orderType': '业务结算明细', 'fileName': '无', 'period': period, 'logId': item['logId'], 'startTime': start_time})
                        if item['accountType'] == '往期应收冲销总数':
                            logger.info('开始下载【往期应收冲销总数】流程')
                            start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                            bill_count = akc_func.get_receive_bill_count(period)
                            param_list.append({'orderType': '往期应收冲销总数', 'fileName': bill_count, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                        if item['accountType'] == '账户出入款记录总数':
                            logger.info('开始下载【账户出入款记录总数】流程')
                            start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                            bill_count = akc_func.get_owner_receive_bill_count(period)
                            param_list.append({'orderType': '账户出入款记录总数', 'fileName': bill_count, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                        if item['accountType'] == '业务结算明细总数':
                            logger.info('开始下载【业务结算明细总数】流程')
                            start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                            bill_count = akc_func.get_business_detail_count(period)
                            param_list.append({'orderType': '业务结算明细总数', 'fileName': bill_count, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                    if len(param_list) > 0:
                        # 编码字符串
                        coding_param = akc_func.encode_param(param_list)
                        # 上传文件
                        uri = "api/v1/ikcReceiveBill/ikcReceiveBillRPAImportV2/{}".format(item['storeCode'])
                        akc_func.upload_file(uri, coding_param, file_list)
                akc_func.close()
    except:
        logger.info(traceback.format_exc())
